package com.zyx.camunda.controller;

import cn.hutool.core.util.IdUtil;
import org.camunda.bpm.engine.RepositoryService;
import org.camunda.bpm.engine.RuntimeService;
import org.camunda.bpm.engine.TaskService;
import org.camunda.bpm.engine.repository.ProcessDefinition;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.camunda.bpm.engine.task.Task;
import org.camunda.bpm.engine.variable.VariableMap;
import org.camunda.bpm.engine.variable.Variables;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Arrays;

/**
 * @author zyx
 * @since 2023/9/27 19:30
 */
@RestController
@RequestMapping("/workflow")
public class WorkflowController {

    @Resource
    private RepositoryService repositoryService;

    @Resource
    private RuntimeService runtimeService;

    @Resource
    private TaskService taskService;

    public static final String TENANT = "zyx";

    @PostMapping("/deploy/{deployId}")
    public String start(@PathVariable("deployId") String deployId) {
        ProcessDefinition processDef = repositoryService
            .createProcessDefinitionQuery()
            .deploymentId(deployId)
            .tenantIdIn(TENANT)
            .singleResult();
        VariableMap variableMap = Variables.createVariables()
            .putValue("assigneeList", Arrays.asList("201", "202", "203"));
        ProcessInstance processInstance = runtimeService
            .startProcessInstanceById(processDef.getId(), IdUtil.getSnowflakeNextIdStr(), variableMap);
        return processInstance.getId();
    }

    @PostMapping("/complete/{procInstId}/{assigneeId}")
    public void complete(@PathVariable("procInstId") String procInstId,@PathVariable("assigneeId") String assigneeId) {
        Task task = taskService.createTaskQuery()
            .processInstanceId(procInstId)
            .taskAssignee(assigneeId)
            .singleResult();
        taskService.complete(task.getId());
    }

}
